import os
import time
import random
import keyboard
from threading import Thread


class SnakeGame:
    def __init__(self, width=20, height=15):
        self.width = width
        self.height = height
        self.reset_game()

    def reset_game(self):
        """重置游戏状态"""
        # 蛇的初始位置和方向
        self.snake = [(self.height // 2, self.width // 2)]
        self.direction = 'RIGHT'
        self.next_direction = 'RIGHT'

        # 食物位置
        self.food = self.generate_food()

        # 游戏状态
        self.score = 0
        self.game_over = False
        self.paused = False

    def generate_food(self):
        """生成食物位置"""
        while True:
            food = (random.randint(1, self.height - 2), random.randint(1, self.width - 2))
            if food not in self.snake:
                return food

    def draw(self):
        """绘制游戏界面"""
        os.system('cls' if os.name == 'nt' else 'clear')

        # 绘制上边界
        print('┌' + '─' * (self.width * 2) + '┐')

        # 绘制游戏区域
        for i in range(self.height):
            print('│', end='')
            for j in range(self.width):
                if (i, j) in self.snake:
                    # 蛇头用不同字符表示
                    if (i, j) == self.snake[0]:
                        print('●', end=' ')
                    else:
                        print('○', end=' ')
                elif (i, j) == self.food:
                    print('★', end=' ')
                else:
                    print('  ', end='')
            print('│')

        # 绘制下边界
        print('└' + '─' * (self.width * 2) + '┘')

        # 显示分数和提示
        print(f"得分: {self.score}")
        print("方向键控制移动，P键暂停，R键重新开始，Q键退出")

        if self.paused:
            print("游戏暂停中...")

    def update(self):
        """更新游戏状态"""
        if self.paused or self.game_over:
            return

        # 更新方向
        self.direction = self.next_direction

        # 计算新的蛇头位置
        head_i, head_j = self.snake[0]
        if self.direction == 'UP':
            new_head = (head_i - 1, head_j)
        elif self.direction == 'DOWN':
            new_head = (head_i + 1, head_j)
        elif self.direction == 'LEFT':
            new_head = (head_i, head_j - 1)
        elif self.direction == 'RIGHT':
            new_head = (head_i, head_j + 1)

        # 检查碰撞
        if (new_head[0] < 0 or new_head[0] >= self.height or
                new_head[1] < 0 or new_head[1] >= self.width or
                new_head in self.snake):
            self.game_over = True
            return

        # 移动蛇
        self.snake.insert(0, new_head)

        # 检查是否吃到食物
        if new_head == self.food:
            self.score += 10
            self.food = self.generate_food()
        else:
            self.snake.pop()

    def handle_input(self):
        """处理键盘输入"""
        while True:
            if keyboard.is_pressed('up') and self.direction != 'DOWN':
                self.next_direction = 'UP'
            elif keyboard.is_pressed('down') and self.direction != 'UP':
                self.next_direction = 'DOWN'
            elif keyboard.is_pressed('left') and self.direction != 'RIGHT':
                self.next_direction = 'LEFT'
            elif keyboard.is_pressed('right') and self.direction != 'LEFT':
                self.next_direction = 'RIGHT'
            elif keyboard.is_pressed('p'):
                self.paused = not self.paused
                time.sleep(0.2)  # 防止频繁切换
            elif keyboard.is_pressed('r'):
                self.reset_game()
                time.sleep(0.2)
            elif keyboard.is_pressed('q'):
                self.game_over = True
                break
            time.sleep(0.05)

    def show_start_screen(self):
        """显示开始界面"""
        os.system('cls' if os.name == 'nt' else 'clear')
        print(" " * 10 + "贪吃蛇游戏")
        print(" " * 5 + "=" * 20)
        print()
        print("游戏说明:")
        print("  - 使用方向键控制蛇的移动")
        print("  - 吃到食物 ★ 可以增加分数")
        print("  - 撞到墙壁或自己的身体游戏结束")
        print()
        print("控制键:")
        print("  - P: 暂停/继续游戏")
        print("  - R: 重新开始游戏")
        print("  - Q: 退出游戏")
        print()
        input("按回车键开始游戏...")

    def show_game_over(self):
        """显示游戏结束界面"""
        os.system('cls' if os.name == 'nt' else 'clear')
        print(" " * 10 + "游戏结束!")
        print(" " * 5 + "=" * 20)
        print()
        print(f"最终得分: {self.score}")
        print()
        print("按 R 键重新开始游戏")
        print("按 Q 键退出游戏")

        while True:
            if keyboard.is_pressed('r'):
                self.reset_game()
                break
            elif keyboard.is_pressed('q'):
                self.game_over = True
                break
            time.sleep(0.1)

    def run(self):
        """运行游戏主循环"""
        self.show_start_screen()

        # 启动输入处理线程
        input_thread = Thread(target=self.handle_input)
        input_thread.daemon = True
        input_thread.start()

        # 游戏主循环
        while not self.game_over:
            self.update()
            self.draw()

            if self.game_over:
                self.show_game_over()
            else:
                time.sleep(0.2)  # 控制游戏速度


if __name__ == "__main__":
    try:
        game = SnakeGame()
        game.run()
    except KeyboardInterrupt:
        print("\n游戏已退出")